package com.kaige.asktaoplugin60.utils;

import com.kaige.asktaoplugin60.config.TcpInitChannel;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务端工具类
 */
@Slf4j
public class ServerUtil {
    
    /**
     * 方法一：基于netty，实现服务端工具，用于接收游戏客户端连接
     * 
     * @param port 服务端监听端口
     * @param bossGroup Boss线程组，用于接收连接
     * @param workerGroup Worker线程组，用于处理连接后的I/O操作
     * @param channelHandler Channel处理器，用于处理网络事件
     * @return ChannelFuture 通道future，可用于监听端口绑定结果
     */
    public static ChannelFuture startServer(int port, NioEventLoopGroup bossGroup, NioEventLoopGroup workerGroup, ChannelHandler channelHandler) {
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    // 设置TCP连接请求队列大小为1024
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    // 启用TCP Keep-Alive机制
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    // 设置发送缓冲区大小为32KB
                    .childOption(ChannelOption.SO_SNDBUF, 32 * 1024)
                    // 设置接收缓冲区大小为32KB
                    .childOption(ChannelOption.SO_RCVBUF, 32 * 1024)
                    // 指定Channel类型为NioServerSocketChannel
                    .channel(NioServerSocketChannel.class)
                    // 设置子处理器，用于处理接收到的连接
                    .childHandler(new TcpInitChannel(channelHandler));
            
            // 绑定端口并启动服务，返回ChannelFuture
            ChannelFuture channelFuture = bootstrap.bind(port).sync();

            log.info("Netty服务端启动成功，监听端口: {}", port);
            return channelFuture;
        } catch (Exception e) {
            log.error("Netty服务端启动失败，端口: {}", port, e);
            throw new RuntimeException("Netty服务端启动失败", e);
        }
    }
}